package cn.wokoba.trigger.http;


import cn.wokoba.controller.IErpOperateService;
import cn.wokoba.controller.dto.ESUserRaffleOrderResponseDTO;
import cn.wokoba.controller.dto.RaffleActivityStageResponseDTO;
import cn.wokoba.controller.dto.UpdateStageActivityStateRequestDTO;
import cn.wokoba.service.activity.model.RaffleActivityStageEntity;
import cn.wokoba.service.activity.service.armory.ActivityArmory;
import cn.wokoba.service.activity.service.state.RaffleActivityStageService;
import cn.wokoba.service.activity.service.state.handler.ActivityStateHandler;
import cn.wokoba.service.querys.model.ESUserRaffleOrderVO;
import cn.wokoba.service.querys.repository.ESUserRaffleOrderRepository;
import cn.wokoba.service.strategy.armory.IStrategyArmory;
import cn.wokoba.types.enums.ResponseCode;
import cn.wokoba.types.model.Response;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

//ERP 运营接口

@Slf4j
@RestController()
@CrossOrigin("${app.config.cross-origin}")
@RequestMapping("/api/${app.config.api-version}/raffle/erp")
@DubboService(version = "1.0.0")
public class ErpOperateController implements IErpOperateService {
    @Autowired
    private ESUserRaffleOrderRepository userRaffleOrderRepository;
    @Autowired
    private ActivityStateHandler activityStateHandler;
    @Autowired
    RaffleActivityStageService raffleActivityStageService;
    @Autowired
    private ActivityArmory activityArmory;
    @Autowired
    private IStrategyArmory strategyArmory;

    /**
     * 查询运营数据，用户抽奖单列表
     * curl --request GET --url 'http://localhost:8098/api/v1/raffle/erp/query_user_raffle_order'
     */
    @GetMapping("/query_user_raffle_order")
    @Override
    public Response<List<ESUserRaffleOrderResponseDTO>> queryUserRaffleOrder() {
        try {
            log.info("查询运营数据，用户抽奖单列表");
            List<ESUserRaffleOrderVO> userRaffleOrderVOList = userRaffleOrderRepository.queryESUserRaffleOrderVOList();

            List<ESUserRaffleOrderResponseDTO> userRaffleOrderResponseDTOS = new ArrayList<>();
            for (ESUserRaffleOrderVO esUserRaffleOrderVO : userRaffleOrderVOList) {
                ESUserRaffleOrderResponseDTO esUserRaffleOrderResponseDTO = new ESUserRaffleOrderResponseDTO();
                esUserRaffleOrderResponseDTO.setUserId(esUserRaffleOrderVO.getUserId());
                esUserRaffleOrderResponseDTO.setActivityId(esUserRaffleOrderVO.getActivityId());
                esUserRaffleOrderResponseDTO.setActivityName(esUserRaffleOrderVO.getActivityName());
                esUserRaffleOrderResponseDTO.setStrategyId(esUserRaffleOrderVO.getStrategyId());
                esUserRaffleOrderResponseDTO.setOrderId(esUserRaffleOrderVO.getOrderId());
                esUserRaffleOrderResponseDTO.setOrderTime(esUserRaffleOrderVO.getOrderTime());
                esUserRaffleOrderResponseDTO.setOrderState(esUserRaffleOrderVO.getOrderState());
                esUserRaffleOrderResponseDTO.setCreateTime(esUserRaffleOrderVO.getCreateTime());
                esUserRaffleOrderResponseDTO.setUpdateTime(esUserRaffleOrderVO.getUpdateTime());
                userRaffleOrderResponseDTOS.add(esUserRaffleOrderResponseDTO);
            }

            return Response.<List<ESUserRaffleOrderResponseDTO>>builder()
                    .code(ResponseCode.SUCCESS.getCode())
                    .info(ResponseCode.SUCCESS.getInfo())
                    .data(userRaffleOrderResponseDTOS)
                    .build();
        } catch (Exception e) {
            log.error("查询运营数据，用户抽奖单列表", e);
            return Response.<List<ESUserRaffleOrderResponseDTO>>builder()
                    .code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .build();
        }
    }

    @PostMapping("/update_stage_activity_2_active")
    @Override
    public Response<Boolean> updateStageActivity2Active(@RequestBody UpdateStageActivityStateRequestDTO requestDTO) {
        try {
            Long id = requestDTO.getId();
            log.info("更新上架活动状态为开启开始 id:{}", id);
            Long activityId = raffleActivityStageService.queryStageActivity2ActiveById(id);

            raffleActivityStageService.updateStageActivity2Active(activityId);
            log.info("更新上架活动状态为开启完成 activityId:{}", activityId);
            boolean assembled = activityArmory.assembleActivitySkuByActivityId(activityId);
            boolean assembledStrategy = strategyArmory.assembleLotteryStrategyByActivityId(activityId);
            log.info("活动数据装配完成 activityId:{} assembled:{} assembledStrategy:{}", activityId, assembled, assembledStrategy);

            return Response.<Boolean>builder()
                    .code(ResponseCode.SUCCESS.getCode())
                    .info(ResponseCode.SUCCESS.getInfo())
                    .data(true)
                    .build();
        } catch (Exception e) {
            log.error("更新上架活动状态为生效开始，失败 id:{}", requestDTO.getId(), e);
            return Response.<Boolean>builder()
                    .code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .build();
        }
    }

    @GetMapping("/query_raffle_activity_stage_list")
    @Override
    public Response<List<RaffleActivityStageResponseDTO>> queryRaffleActivityStageList() {
        try {
            List<RaffleActivityStageResponseDTO> raffleActivityStageResponseDTOS = new ArrayList<>();
            List<RaffleActivityStageEntity> raffleActivityStageEntities = raffleActivityStageService.queryStageActivityList();
            for (RaffleActivityStageEntity raffleActivityStage : raffleActivityStageEntities) {
                RaffleActivityStageResponseDTO raffleActivityStageResponseDTO = RaffleActivityStageResponseDTO.builder()
                        .id(raffleActivityStage.getId())
                        .channel(raffleActivityStage.getChannel())
                        .source(raffleActivityStage.getSource())
                        .activityId(raffleActivityStage.getActivityId())
                        .state(raffleActivityStage.getState())
                        .build();
                raffleActivityStageResponseDTOS.add(raffleActivityStageResponseDTO);
            }

            Response<List<RaffleActivityStageResponseDTO>> response = Response.<List<RaffleActivityStageResponseDTO>>builder()
                    .code(ResponseCode.SUCCESS.getCode())
                    .info(ResponseCode.SUCCESS.getInfo())
                    .data(raffleActivityStageResponseDTOS)
                    .build();

            log.info("查询上架活动数据 {}", JSON.toJSONString(response));

            return response;
        } catch (Exception e) {
            log.error("查询上架活动数据失败", e);
            return Response.<List<RaffleActivityStageResponseDTO>>builder()
                    .code(ResponseCode.UN_ERROR.getCode())
                    .info(ResponseCode.UN_ERROR.getInfo())
                    .build();
        }
    }

}
